import { Ref } from 'vue'
import { useTheme } from '@/store/modules/theme'

export function useFullscreen(target: Ref<HTMLDivElement | null>) {
  const theme = useTheme()

  let styleCache: any = {}
  const isFullscreen = ref(false)

  const fullscreen = () => {
    const { position, left, top, width, height } = target.value?.style || {}
    styleCache = { position, left, top, width, height }
    setStyle()
    isFullscreen.value = true
    document.addEventListener('keyup', keypressCallback)
  }

  const exit = () => {
    setStyleFn(styleCache)
    isFullscreen.value = false
    document.removeEventListener('keyup', keypressCallback)
  }

  const fullScreenChange = () => {
    if (!isFullscreen.value) {
      fullscreen()
    } else {
      exit()
    }
  }

  const keypressCallback = (e) => {
    if (e.key === 'Escape') {
      exit()
    }
  }

  const setStyle = () => {
    setStyleFn({
      position: 'fixed',
      left: '0',
      right: '0',
      top: '0',
      zIndex: 999,
      width: '100vw',
      height: '100vh',
      padding: '10px',
      overflow: 'auto',
      backgroundColor: theme.darkMode === 'dark' ? '#101014' : '#fff'
    })
  }

  const setStyleFn = (style) => {
    if (target.value) {
      target.value.style.position = style.position || null
      target.value.style.left = style.left || null
      target.value.style.top = style.top || null
      target.value.style.zIndex = style.zIndex || null
      target.value.style.width = style.width || null
      target.value.style.height = style.height || null
      target.value.style.padding = style.padding || null
      target.value.style.overflow = style.overflow || null
      target.value.style.backgroundColor = style.backgroundColor || null
    }
  }

  return {
    isFullscreen,
    fullScreenChange
  }
}
